﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;

namespace RMH.DataAccess.AdoNet
{
    public static class AdoDataHelper
    {
        public static string GetConnectionString()
        {
            return ConfigurationManager.AppSettings["ConnectionString"] ?? "";
        }

        public static void ExecuteScript(string scriptName)
        {
            string rmhRootDir = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("RMH") + 3);
            ExecuteScript(scriptName, rmhRootDir);
        }

        public static void ExecuteScript(string scriptName, string directory)
        {
            using (SqlConnection conn = new SqlConnection(GetConnectionString()))
            {                                
                string sqlScriptPath = directory + @"\RMH.DataAccess\AdoNet\Scripts\" + scriptName;
                string sqlScript = File.ReadAllText(sqlScriptPath);
                string[] sqlBatches = sqlScript.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);

                conn.Open();
                foreach (string sqlBatch in sqlBatches)
                {
                    SqlCommand cmd = new SqlCommand(sqlBatch, conn);
                    cmd.ExecuteNonQuery();
                }
                conn.Close();
            }
        }
    }
}
